package com.stray.crawl.utils;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

public class DataUtils {

	public static boolean isEmpty(String str) {
		return str == null || str.length() == 0;
	}

	public static boolean isEmpty(Collection<?> collection) {
		return collection == null || collection.isEmpty();
	}

	public static boolean contains(Enum<?>[] enums, String str) {
		for (Enum<?> e : enums) {
			if (e.name().equals(str)) {
				return true;
			}
		}

		return false;
	}

	public static boolean isNumeric(Object obj) {
		if (obj != null) {
			if (obj instanceof Number) {
				return true;
			} else if (obj instanceof String) {
				return isNumeric((String) obj);
			}
		}

		return false;
	}
	public static boolean isNumeric(String str) {
		if (!isEmpty(str)) {
			for (int i = 0; i < str.length(); i ++) {
				if (!Character.isDigit(str.charAt(i))) {
					return false;
				}
			}

			return true;
		}

		return false;
	}

	public static String substr(String str, String fm, String to) {
		int fmIdx = str.indexOf(fm) + fm.length();
		int toIdx = str.indexOf(to, fmIdx);

		fmIdx = fmIdx >= 0 ? fmIdx : 0;
		toIdx = toIdx >= 0 ? toIdx : str.length();

		return str.substring(fmIdx, toIdx);
	}

	public static String substrBefore(String str, String to) {
		int toIdx = str.indexOf(to);
		toIdx = toIdx >= 0 ? toIdx : str.length();
		return str.substring(0, toIdx);
	}

	public static String substrAfter(String str, String fm) {
		int fmIdx = str.indexOf(fm) + fm.length();
		fmIdx = fmIdx >= 0 ? fmIdx : 0;
		return str.substring(fmIdx);
	}

	public static String joins(Iterable<?> objs, String delimiter) {
		StringBuffer buf = new StringBuffer();

		if (objs != null) {
			for (Object obj : objs) {
				if (buf.length() > 0) {
					buf.append(delimiter);
				}

				buf.append(obj);
			}
		}

		return buf.toString();
	}

	public static String joins(Object[] objs, String delimiter) {
		StringBuffer buf = new StringBuffer();

		if (objs != null) {
			for (Object obj : objs) {
				if (buf.length() > 0) {
					buf.append(delimiter);
				}

				buf.append(obj);
			}
		}

		return buf.toString();
	}

	public static String[] copyStringArray(String[] array) {
		String[] newArray;

		if (array != null) {
			newArray = new String[array.length];
			System.arraycopy(array, 0, newArray, 0, array.length);
		} else {
			newArray = new String[0];
		}

		return newArray;
	}

	public static <T> Map<T, T> toMap(T... objs) {
		Map<T, T> map = new LinkedHashMap<T, T>();

		for (int i = 0; i < objs.length - 1; i += 2) {
			map.put(objs[i], objs[i + 1]);
		}

		return map;
	}

	public static String valueOf(String str, String defValue) {
		return str != null ? str : defValue;
	}

	public static int valueOf(String str, int defValue) {
		return str != null && isNumeric(str) ? Integer.valueOf(str) : defValue;
	}

}